package cn.myjerry.io.byteIO;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
 * 文件操作工具类
 * @author Jerry
 */
public class FileUtil {
	/**
	 * 文件拷贝
	 * @param srcPath
	 * @param destPath
	 * @throws IOException
	 */
	public static void copyFile(String srcPath, String destPath) throws IOException {
		File src = new File(srcPath);
		File dest = new File(destPath);
		copyFile(src, dest);
	}
	/**
	 * 文件拷贝
	 * @param src
	 * @param newSrc
	 * @throws IOException
	 */
	public static void copyFile(File src, File dest) throws IOException {
		if(!src.isFile()) {
			throw new IOException("只能拷贝文件");
		}
		if(dest.isDirectory()) {
			throw new IOException("不能建立与文件夹同名的文件");
		}
		InputStream is = null;
		OutputStream os = null;
		is = new BufferedInputStream(new FileInputStream(src));
		os = new BufferedOutputStream(new FileOutputStream(dest, true));
		byte[] car = new byte[1024];
		int len = 0;
		while(-1 != (len = is.read(car))) {
			os.write(car, 0, len);
			os.flush();
		}
		is.close();
		os.close();
	}
	/**
	 * 文件夹的拷贝
	 * @param srcPath
	 * @param destPath
	 * @throws IOException
	 */
	public static void copyDir(String srcPath, String destPath) throws IOException {
		File src = new File(srcPath);
		File dest = new File(destPath);
		if(src.isDirectory()) {
			dest = new File(destPath, src.getName());
			if(src.getAbsolutePath().contains(dest.getAbsolutePath())) {
				System.out.println("父目录不能拷贝到子目录");
				return;
			}
		}
		copyDirDetail(src, dest);
	}
	/**
	 * 文件夹拷贝细节
	 * @param src
	 * @param dest
	 * @throws IOException
	 */
	public static void copyDirDetail(File src, File dest) throws IOException {
		if(src.isFile()) {
			copyFile(src, dest);
		} else if(src.isDirectory()) {		// 确保目标文件夹存在
			dest.mkdirs();
			for(File temp:src.listFiles()) {
				copyDirDetail(temp, new File(dest, temp.getName()));
			}
		}
	}
}
